<template>
  <div class="common_block_div">
    <!-- 操作按钮 -->
    <div class="common_button flex_ac">
      <div class="right_button margin_a flex">
        <a href="javascript:;" class="color_blue" @click="handleAdd" v-if="have_auth('/policy_management/policy/index/add')">新增</a>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="newsList" style="width: 100%">
      <el-table-column label="新闻标题" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="所属分类" prop="category_txt" :show-overflow-tooltip="true" />
      <el-table-column label="发布时间" prop="update_time" />
      <el-table-column label="操作" width="200px" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)" v-if="have_auth('/policy_management/policy/index/detail')">查看</el-button>
          <el-button size="mini" type="text" @click="handleEdit(scope.row)" v-if="have_auth('/policy_management/policy/index/edit')">编辑</el-button>
          <el-button size="mini" type="text" style="color: #F56C6C;" @click="handleDelete(scope.row)" v-if="have_auth('/policy_management/policy/index/del')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="newsListTotal > 0" :total="newsListTotal" :page.sync="queryParams.page"
      :limit.sync="queryParams.limit" @pagination="getNewsList" />

    <!-- 详情弹框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" title="新闻详情" :visible.sync="detailVisible" width="800px"
      append-to-body @closed="handleDetailClosed">
      <div v-loading="detailLoading" class="detail-content">
        <div v-if="detailData.title" class="detail-header">
          <h3 class="detail-title">{{ detailData.title }}</h3>
          <div class="detail-meta">
            <span v-if="detailData.update_time">发布时间：{{ detailData.update_time }}</span>
            <span v-if="detailData.author" class="margin_l20">发布人：{{ detailData.author }}</span>
          </div>
        </div>
        <div class="detail-body">
          <div v-html="detailContent"></div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" :title="formDialogTitle" :visible.sync="formVisible"
      width="900px" append-to-body @closed="handleFormClosed">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入标题" maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="分类" prop="category_id">
              <el-select v-model="formData.category_id" placeholder="请选择分类" clearable filterable style="width: 100%">
                <el-option v-for="item in categoryOptions" :key="item.id" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详情内容" prop="content">
              <Editor v-model="formData.content" :min-height="300" :upload-url="editorUploadUrl" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="formSubmitting">
          {{ formSubmitting ? '保存中···' : '确定' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination/index.vue";
import Editor from "@/components/Editor/index.vue";
// 导入政策新闻API
import policyApi from "@/api/policy";

export default {
  name: 'PolicyManagement',
  components: {
    Pagination,
    Editor
  },
  props: {
    projectId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      newsList: [],
      newsListTotal: 0,
      queryParams: {
        page: 1,
        limit: 16
      },
      // 详情弹框相关
      detailVisible: false,
      detailLoading: false,
      detailData: {},
      detailContent: '',
      // 添加/编辑弹框相关
      formVisible: false,
      formDialogTitle: '新增新闻',
      formSubmitting: false,
      formData: {
        id: '',
        title: '',
        category_id: '',
        content: ''
      },
      formRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        category_id: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入详情内容', trigger: 'blur' }
        ]
      },
      // 分类选项
      categoryOptions: [],
      // 编辑器上传地址
      editorUploadUrl: '/api/Upload/image'
    }
  },
  methods: {
    /** 查看新闻详情 */
    handleView(row) {
      const _this = this;
      if (!row.id) {
        this.$message.warning('无法查看该数据');
        return;
      }

      // 打开详情弹框
      this.detailVisible = true;
      this.detailLoading = true;
      this.detailData = {};
      this.detailContent = '';

      // 调用API获取新闻详情
      policyApi.newsDetail({ id: row.id }).then((res) => {
        if (res && res.message) {
          _this.detailData = res.message;
          // 处理富文本内容，添加图片路径前缀（如果需要）
          let content = res.message.content || '';
          // 如果内容中有图片路径需要处理，可以使用 add_upload_http 方法
          if (content && typeof _this.add_upload_http === 'function') {
            content = _this.add_upload_http(content);
          }
          _this.detailContent = content;
        } else {
          _this.$message.error('获取详情失败');
          _this.detailVisible = false;
        }
        _this.detailLoading = false;
      }).catch((error) => {
        console.error('获取详情失败:', error);
        _this.$message.error('获取详情失败');
        _this.detailLoading = false;
        _this.detailVisible = false;
      });
    },

    /** 详情弹框关闭后的回调 */
    handleDetailClosed() {
      this.detailData = {};
      this.detailContent = '';
    },

    /** 添加新闻 */
    handleAdd() {
      this.resetForm();
      this.formDialogTitle = '新增新闻';
      this.formVisible = true;
    },

    /** 编辑新闻 */
    handleEdit(row) {
      const _this = this;
      if (!row.id) {
        this.$message.warning('无法编辑该数据');
        return;
      }

      // 重置表单
      this.resetForm();
      this.formDialogTitle = '编辑新闻';

      // 调用API获取详情数据
      policyApi.newsDetail({ id: row.id }).then((res) => {
        if (res && res.message) {
          _this.formData = {
            id: res.message.id || '',
            title: res.message.title || '',
            category_id: res.message.category_id || '',
            content: res.message.content || ''
          };
          _this.formVisible = true;
        } else {
          _this.$message.error('获取详情失败');
        }
      }).catch((error) => {
        console.error('获取详情失败:', error);
        _this.$message.error('获取详情失败');
      });
    },

    /** 重置表单 */
    resetForm() {
      this.formData = {
        id: '',
        title: '',
        category_id: '',
        content: ''
      };
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
    },

    /** 表单弹框关闭后的回调 */
    handleFormClosed() {
      this.resetForm();
    },

    /** 提交表单 */
    handleSubmit() {
      const _this = this;
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.formSubmitting = true;

          // 构建提交数据
          const submitData = {
            title: this.formData.title,
            category_id: this.formData.category_id,
            content: this.formData.content
          };

          // 如果是编辑，需要传id
          if (this.formData.id) {
            submitData.id = this.formData.id;
          }

          // 调用API创建或更新
          policyApi.newsCreateOrUpdate(submitData).then((res) => {
            if (res) {
              _this.$message.success(this.formData.id ? '修改成功' : '添加成功');
              _this.formVisible = false;
              _this.getNewsList();
            }
            _this.formSubmitting = false;
          }).catch((error) => {
            console.error('提交失败:', error);
            _this.$message.error('提交失败');
            _this.formSubmitting = false;
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    /** 获取分类列表 */
    getCategoryList() {
      const _this = this;
      // 调用API获取分类列表（不分页）
      policyApi.categoryList().then((res) => {
        if (res && res.message) {
          _this.categoryOptions = res.message.data || res.message || [];
        }
      }).catch((error) => {
        console.error('获取分类列表失败:', error);
      });
    },

    /** 删除新闻 */
    handleDelete(row) {
      const _this = this;
      if (!row.id) {
        this.$message.warning('无法删除该数据');
        return;
      }
      this.$confirm('确定要删除该新闻吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除API
        policyApi.newsDelete({ id: row.id }).then((res) => {
          if (res) {
            _this.$message.success('删除成功');
            _this.getNewsList();
          }
        }).catch((error) => {
          console.error('删除失败:', error);
          _this.$message.error('删除失败');
        });
      }).catch(() => {
        // 用户取消删除
      });
    },

    /** 获取新闻列表 */
    getNewsList() {
      const _this = this;
      this.loading = true;

      // 构建查询参数
      const params = {
        ...this.queryParams
      };

      // 如果有 projectId，添加到查询参数中
      if (this.projectId) {
        params.project_id = this.projectId;
      }

      // 调用API获取新闻列表
      policyApi.newsList(params).then(function (res) {
        if (res && res.message) {
          _this.newsList = res.message.data || [];
          _this.newsListTotal = res.message.total || 0;
        }
        _this.loading = false;
      }).catch(function (error) {
        console.error('获取新闻列表失败:', error);
        _this.loading = false;
        // 如果接口失败，可以显示错误提示
        // _this.$message.error('获取新闻列表失败');
      });
    }
  },
  mounted() {
    this.getNewsList();
    this.getCategoryList();
  }
}
</script>

<style scoped>
/* 详情弹框样式 */
.detail-content {
  min-height: 200px;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.detail-title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 10px 0;
}

.detail-meta {
  font-size: 14px;
  color: #909399;
}

.detail-body {
  padding: 20px 0;
  line-height: 1.8;
  color: #606266;
  max-height: 450px;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 富文本内容样式 */
.detail-body>>>img {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 10px 0;
}

.detail-body>>>p {
  margin: 10px 0;
}

.detail-body>>>h1,
.detail-body>>>h2,
.detail-body>>>h3,
.detail-body>>>h4,
.detail-body>>>h5,
.detail-body>>>h6 {
  margin: 15px 0 10px 0;
  font-weight: bold;
}

.detail-body>>>ul,
.detail-body>>>ol {
  margin: 10px 0;
  padding-left: 30px;
}

.detail-body>>>table {
  width: 100%;
  border-collapse: collapse;
  margin: 15px 0;
}

.detail-body>>>table td,
.detail-body>>>table th {
  border: 1px solid #ddd;
  padding: 8px;
}

.detail-body>>>table th {
  background-color: #f5f7fa;
  font-weight: bold;
}
</style>
